package com.tripspins.app;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tripspins.app.adapter.AttachmentListAdapter;
import com.tripspins.app.bo.Attachment;
import com.tripspins.app.bo.Contact;
import com.tripspins.app.bo.CurrentWeather;
import com.tripspins.app.bo.Pin;
import com.tripspins.app.bo.Route;
import com.tripspins.app.bo.Trip;
import com.tripspins.app.bo.User;
import com.tripspins.app.dao.AttachmentDAO;
import com.tripspins.app.dao.PinDAO;
import com.tripspins.app.dao.TripDAO;
import com.tripspins.app.dao.UserDAO;
import com.tripspins.app.exception.NoConnectionException;
import com.tripspins.app.exception.OfflineModeException;
import com.tripspins.app.helper.ConstantsHelper;
import com.tripspins.app.helper.DbHelper;
import com.tripspins.app.helper.FILE_TYPE;
import com.tripspins.app.helper.FileHelper;
import com.tripspins.app.helper.HttpHelper;
import com.tripspins.app.helper.LocationHelper;
import com.tripspins.app.helper.MapsAPIHelper;
import com.tripspins.app.helper.MenuHelper;
import com.tripspins.app.helper.NewAttachmentsHelper;
import com.tripspins.app.helper.TRIP_STATUS;
import com.tripspins.app.helper.ThumbnailsHelper;
import com.tripspins.app.helper.WeatherHelper;
import com.tripspins.app.interfaces.OnFragmentInteractionListener;
import com.tripspins.app.interfaces.OnTaskCompleted;
import com.tripspins.app.interfaces.UpdateMapListener;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NewPinActivity extends Activity implements UpdateMapListener, OnTaskCompleted {
    private android.app.FragmentTransaction fragmentTransaction;
    private static final String ARG_FRAG_TRAN = "arg_frag_tran";
    private FragmentManager fragmentManager;
    private MapFragment mapFragment;
    private Pin newPin;
    private WeatherHelper weatherHelper;
    private TextView pinTitle;
    private TextView pinNote;
    private Uri fileUri;
    private GridView lstAttachments;
    private LocationHelper locationHelper;


    TripDAO tripDao;
    UserDAO userDao;
    PinDAO pinDao;
    ArrayList<Trip> trips;
    boolean isOnTheRoad;
    boolean isAuthenticated;
    DbHelper dbHelper;
    SharedPreferences settings;
    SQLiteDatabase database;
    User loggedUser;
    AttachmentDAO attachmentDAO;



    public NewPinActivity() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_pin);
        mapFragment = MapFragment.newInstance();
        fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().add(R.id.map_new_pin_holder,mapFragment).commit();
        pinTitle = (TextView)findViewById(R.id.new_pin_title);
        pinNote = (TextView)findViewById(R.id.new_pin_edit_note);
        lstAttachments =(GridView)findViewById(R.id.new_pin_list_attachments);
        getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);



        try{
            isOnTheRoad = this.getIntent().getBooleanExtra("IS_ON_THE_ROAD",false);
            newPin = savedInstanceState.getParcelable("newPin");
            fileUri = savedInstanceState.getParcelable("fileUri");
        }
        catch(Exception e){
            newPin = new Pin();
        }
        loadListAttachments();
    }

    @Override
    public void onResume() {
        super.onResume();
        locationHelper = LocationHelper.getInstance(this, this);
        loadListAttachments();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        super.onPrepareOptionsMenu(menu);
        menu.clear();
        loadTopMenu();
        getMenuInflater().inflate(R.menu.menu_add_pin_bottom, menu);
        return true;
    }

    private void loadTopMenu() {
        try {
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            getActionBar().setCustomView(inflater.inflate(R.layout.top_menu_new_pin, null));
            ImageButton btnSavePin = (ImageButton)getActionBar().getCustomView()
                    .findViewById(R.id.menu_save_pin);
            btnSavePin.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    validateFields();

                }
            });
        }catch (Exception e){}
    }

    private void validateFields() {
        if(newPin.getLatLng() != null) {
            newPin.setTitle(pinTitle.getText().toString());
            newPin.setTextNote(pinNote.getText().toString());
            saveNewPin();
        }else{Toast.makeText(this,"aaa",Toast.LENGTH_LONG);}
    }

    private void saveNewPin() {
        if(isOnTheRoad) {
            if (database == null || !database.isOpen()) {
                dbHelper = new DbHelper(this);
                database = dbHelper.getWritableDatabase();
            }
            tripDao = new TripDAO(database);
            pinDao = new PinDAO(database);
            Trip trip = tripDao.getTrip();
            newPin.setId(pinDao.persist(trip.getId(), newPin));
            saveTempFiles(trip.getId(), newPin);
            attachmentDAO = new AttachmentDAO(database);
            attachmentDAO.persist(newPin.getId(), newPin.getAttachments());

        }
        locationHelper.stopListening();
        finish();
    }

    private void saveTempFiles(long tripId, Pin newPin) {
        FileHelper fileHelper = new FileHelper(this);
        fileHelper.persistTempFiles(tripId, newPin.getId());
        for(Attachment att : newPin.getAttachments())
        {
            if(att.getContact()==null)
                att.setPath(fileHelper.getAttachmentsDirectory(tripId,newPin.getId()).getPath() + "/" + att.getFileName());
        }
        fileHelper.cleanTempFolders();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if(newPin.getLatLng()!= null)
            outState.putParcelable("newPin", newPin);
        outState.putParcelable("fileUri",fileUri);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        NewAttachmentsHelper newAttachmentsHelper = new NewAttachmentsHelper(this);
        switch (item.getItemId()) {
            case R.id.menu_att_camera:
                fileUri = newAttachmentsHelper.takePicture();
                return true;
            case R.id.menu_att_camera_video:
                fileUri = newAttachmentsHelper.recordVideo();
                return true;
            case R.id.menu_att_contact:
                newAttachmentsHelper.meetContact();
                return true;
            case R.id.menu_att_voice:
                fileUri = newAttachmentsHelper.recordAudio();
                return true;
            case R.id.menu_att_file:
                newAttachmentsHelper.pickImage();
                return true;
            default:
                return true;
        }
    }

    @Override
    public void updateMapLocation(LatLng latLng) {
        try {
            mapFragment.getMap().clear();
            newPin.setLatLng(latLng);
            MarkerOptions markerOptions = MapsAPIHelper.getMarker(latLng);
            Marker marker = mapFragment.getMap().addMarker(markerOptions);
            LatLngBounds bounds = new LatLngBounds(latLng, latLng);
            final CameraUpdate location = CameraUpdateFactory.newLatLngBounds(bounds, 1000, 1000, 300);
            final CameraUpdate zoom = CameraUpdateFactory.newLatLngZoom(latLng, 14.0f);
            mapFragment.getMap().moveCamera(location);
            mapFragment.getMap().moveCamera(zoom);
            mapFragment.getView().getViewTreeObserver().addOnGlobalLayoutListener(
                    new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            try {
                                mapFragment.getMap().animateCamera(zoom);
                            } catch (Exception e) {
                            }
                        }
                    });
            weatherHelper = new WeatherHelper(this);
            weatherHelper.getWeather(latLng);
        }catch (Exception e){
            Log.e("TP",e.getMessage());
        }
    }

    @Override
    public void onTaskCompleted(Route r) {

    }

    @Override
    public void onTaskCompleted(CurrentWeather w) {
        newPin.setCurrentWeather(w);
        HttpHelper httpHelper = new HttpHelper();
        try {
            httpHelper.getBitmap(newPin.getCurrentWeather().getWeatherIconUrl(), this,this);
        } catch (OfflineModeException e) {
            e.printStackTrace();
        } catch (NoConnectionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTaskCompleted(Bitmap bmp) {
        try {
            FileHelper fileHelper = new FileHelper(this);
            File weatherIcon = fileHelper.saveWeatherIcon();
            ThumbnailsHelper.saveBitmap(bmp, weatherIcon);
        }catch (Exception e){}
    }

    @Override
    public void onTaskCompleted(Attachment att) {

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            NewAttachmentsHelper newAttachmentsHelper = new NewAttachmentsHelper(this);
            switch(requestCode){
                case ConstantsHelper.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
                    newPin.addAttachment(newAttachmentsHelper.getNewPicture(fileUri));
                    break;
                case ConstantsHelper.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
                    newPin.addAttachment(newAttachmentsHelper.getNewVideo(fileUri));
                    break;
                case ConstantsHelper.CAPTURE_AUDIO_ACTIVITY_REQUEST_CODE:
                    newPin.addAttachment(newAttachmentsHelper.getNewAudio(data));
                    break;
                case ConstantsHelper.CONTACTS_ACTIVITY_REQUEST_CODE:
                    newPin.addAttachment(newAttachmentsHelper.getContact(data));
                    break;
                case ConstantsHelper.FACEBOOK_CONTACTS_ACTIVITY_REQUEST_CODE:
                    newPin.getAttachments().addAll(
                            newAttachmentsHelper.getFacebookContacts(
                                    ((GlobalState)getApplication()).getSelectedUsers()));
                    break;
                case ConstantsHelper.PICK_IMAGE_ACTIVITY_REQUEST_CODE:
                    newPin.addAttachment(newAttachmentsHelper.getPickedImage(data));
                    break;
            }
            loadListAttachments();
            loadTopMenu();
        }
    }

    public void loadListAttachments(){
        AttachmentListAdapter attachmentListAdapter = new AttachmentListAdapter(this, newPin.getAttachments());
        attachmentListAdapter.registerDataSetObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                super.onChanged();
            }
        });
        lstAttachments.setAdapter(attachmentListAdapter);
    }

    @Override
    public void onBackPressed() {
        locationHelper.stopListening();
        super.onBackPressed();
    }
}
